//package com.pug.order.nacos;
//
//import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
//import com.alibaba.cloud.nacos.NacosServiceInstance;
//import com.alibaba.nacos.api.exception.NacosException;
//import com.alibaba.nacos.api.naming.NamingService;
//import com.alibaba.nacos.api.naming.pojo.Instance;
//import com.alibaba.nacos.client.naming.NacosNamingService;
//import com.alibaba.nacos.client.naming.core.Balancer;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.ObjectProvider;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.cloud.client.ServiceInstance;
//import org.springframework.cloud.client.loadbalancer.DefaultResponse;
//import org.springframework.cloud.client.loadbalancer.EmptyResponse;
//import org.springframework.cloud.client.loadbalancer.Request;
//import org.springframework.cloud.client.loadbalancer.Response;
//import org.springframework.cloud.loadbalancer.core.NoopServiceInstanceListSupplier;
//import org.springframework.cloud.loadbalancer.core.RoundRobinLoadBalancer;
//import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
//import org.springframework.util.CollectionUtils;
//import reactor.core.publisher.Mono;
//
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Objects;
//import java.util.stream.Collectors;
//
///**
// * @program: xq_pug_alibabacloud_parent
// * @description: 根据不同的集群名称调用规则
// * @author: Mr.Ren
// * @create: 2023-04-16 21:58
// **/
//@Slf4j
//public class RgsNacosClusterNameRoute extends RoundRobinLoadBalancer {
//
//    //当前的服务实例
//    private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;
//    //获取实例服务名
//    private String serviceId;
//
//    @Autowired
//    private NacosDiscoveryProperties nacosDiscoveryProperties;
//
//
//    public RgsNacosClusterNameRoute(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider, String serviceId) {
//        super(serviceInstanceListSupplierProvider, serviceId);
//        this.serviceId = serviceId;
//        this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
//    }
//
//    /**
//     * 核心逻辑：覆盖父类的实例选择方法（这里就是我们自定义负载逻辑的核心）
//     * 根据集群名称进行服务的负载
//     * 本地有就调用本地的实例，本地每月就跨服务调用其他实例，都没有那就报错
//     *
//     * @param request
//     * @return
//     */
//    @Override
//    public Mono<Response<ServiceInstance>> choose(Request request) {
//        try {
//
//            ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider.getIfAvailable(NoopServiceInstanceListSupplier::new);
//
//            return supplier.get(request).next().map(serviceInstances -> getInstanceResponse(serviceInstances, request));
//
//        } catch (Exception e) {
//            //父类轮询负载逻辑，这里不要删除，如果该方法有任何错误，那么就走默认的父类轮询
//            return super.choose(request);
//        }
//
//
//    }
//
//
//    private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> instances, Request request) {
//        try {
//            //1.当前实例为空
//            if (instances.isEmpty()) {
//                if (log.isWarnEnabled()) {
//                    log.warn("No servers available for service: " + this.serviceId);
//                }
//
//                return new EmptyResponse();
//            }
//            //2. 拿到当前服务的实例的集群名称
//            String currentClusterName = nacosDiscoveryProperties.getClusterName();
//            String groupName = nacosDiscoveryProperties.getGroup();
//
//            //3.获取nacos中所有的实例
//
//            NamingService namingService = new NacosNamingService(nacosDiscoveryProperties.getNacosProperties());
//            //根据serviceId过滤获取该服务所有健康的实例
//            List<Instance> allInstances = namingService.selectInstances(serviceId, groupName,true);
//            if (CollectionUtils.isEmpty(allInstances)) {
//                log.error("未找到该服务实例，serviceId:{}", serviceId);
//                return new EmptyResponse();
//            }
//
//            List<Instance> sameClusterInstances = allInstances.stream()
//                    .filter(q -> Objects.equals(q.getClusterName(), currentClusterName))
//                    .collect(Collectors.toList());
//
//            List<Instance> chooseInstances = new ArrayList<>();
//            if (CollectionUtils.isEmpty(sameClusterInstances)) {
//
//                //跨集群调用
//                chooseInstances = allInstances;
//                log.info("当前实例为跨集群调用：clusterName:{},serviceId:{}", currentClusterName, serviceId);
//            } else {
//                //同城调用
//                chooseInstances = sameClusterInstances;
//                log.info("当前实例为同集群调用：clusterName:{},serviceId:{}", currentClusterName, serviceId);
//            }
//
//            //按照权重返回实例
//            Instance selectInstance = ExpandBalance.getHostByRandomWeightChoose(chooseInstances);
//            //对象转化
//            NacosServiceInstance nacosServiceInstance = new NacosServiceInstance();
//            nacosServiceInstance.setHost(selectInstance.getIp());
//            nacosServiceInstance.setMetadata(selectInstance.getMetadata());
//            nacosServiceInstance.setPort(selectInstance.getPort());
//            nacosServiceInstance.setServiceId(selectInstance.getServiceName());
//
//            //返回选中的实例
//            return new DefaultResponse(nacosServiceInstance);
//
//        } catch (NacosException e) {
//            log.error("未找到服务实例");
//            return null;
//        }
//
//    }
//
//}
//
//class ExpandBalance extends Balancer {
//    public static Instance getHostByRandomWeightChoose(List<Instance> hosts) {
//        return getHostByRandomWeight(hosts);
//    }
//}
